import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'

// 文件类型接口
export interface FileItem {
  id: number;
  type: 'folder' | 'image' | 'video' | 'music' | 'file';
  name: string;
  size: string;
  time: string;
}

// 导航菜单类型接口
export interface NavMenu {
  id: number;
  icon: string;
  text: string;
  active: boolean;
}

// 用户信息接口
export interface UserInfo {
  name: string;
  avatar: string;
  storage: {
    used: number;
    total: number;
    percentage: number;
  };
}

// 后端文件响应接口
interface FileResponse {
  id: number;
  type: 'folder' | 'image' | 'video' | 'music' | 'file';
  name: string;
  size: number;
  modifiedTime: string;
}

// 后端API基础URL
const BASE_URL = 'http://localhost:8080';

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref<UserInfo>({
    name: '加载中...',
    avatar: 'https://picsum.photos/200/200?random=1',
    storage: {
      used: 0,
      total: 1024,
      percentage: 0,
    },
  });

  // 文件列表
  const fileList = ref<FileItem[]>([]);
  
  // 导航菜单
  const navMenus = ref<NavMenu[]>([
    { id: 1, icon: 'home', text: '首页', active: true },
    { id: 2, icon: 'folder', text: '我的文件', active: false },
    { id: 3, icon: 'image', text: '图片', active: false },
    { id: 4, icon: 'video', text: '视频', active: false },
    { id: 5, icon: 'music', text: '音乐', active: false },
    { id: 6, icon: 'file', text: '文档', active: false },
    { id: 7, icon: 'trash', text: '回收站', active: false },
  ]);

  // 加载用户信息
  async function loadUserInfo() {
    try {
      // 获取本地存储的用户ID和token
      const userId = localStorage.getItem('userid');
      const token = localStorage.getItem('token');
      
      if (!userId || !token) {
        console.error('未找到用户凭据，请重新登录');
        return;
      }
      
      const response = await axios.get(`${BASE_URL}/user/info`, {
        headers: { userid: userId, token: token }
      });
      
      if (response.data.code === 1) {
        const userData = response.data.data;
        // 更新用户信息
        userInfo.value = {
          name: userData.username || '用户',
          avatar: userData.avatar || 'https://picsum.photos/200/200?random=1',
          storage: {
            used: Math.round(userData.userSpace / (1024 * 1024 * 1024)) || 0, // 转换为GB
            total: 1024, // 默认1TB
            percentage: (userData.userSpace / (1024 * 1024 * 1024 * 1024)) * 100 || 0,
          },
        };
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  }

  // 加载文件列表
  async function loadFileList(folderId = 0) {
    try {
      const userId = localStorage.getItem('userid');
      const token = localStorage.getItem('token');
      
      if (!userId || !token) {
        console.error('未找到用户凭据，请重新登录');
        return;
      }
      
      const response = await axios.get(`${BASE_URL}/file/list`, {
        params: { folderId },
        headers: { userid: userId, token: token }
      });
      
      if (response.data.code === 1) {
        fileList.value = response.data.data.map((file: FileResponse) => ({
          id: file.id,
          type: file.type,
          name: file.name,
          size: file.size === 0 ? '-' : formatFileSize(file.size),
          time: new Date(file.modifiedTime).toLocaleString()
        }));
      }
    } catch (error) {
      console.error('加载文件列表失败:', error);
    }
  }

  // 格式化文件大小
  function formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  return { 
    userInfo, 
    fileList, 
    navMenus, 
    loadUserInfo, 
    loadFileList 
  };
});
